<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="一级品类" prop="oneGenreId">
        <el-select
          v-model="queryParams.oneGenreId"
          placeholder="请选择一级品类"
          clearable
          @change="handleOneProductGenreChange"
        >
          <el-option
            v-for="oneGenre in oneGenrees"
            :key="oneGenre.genreId"
            :label="oneGenre.name"
            :value="oneGenre.genreId"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="二级品类" prop="twoGenreId">
        <el-select
          v-model="queryParams.twoGenreId"
          placeholder="请选择二级品类"
          :disabled="twoGenrees.length === 0"
        >
          <el-option
            v-for="twoGenre in twoGenrees"
            :key="twoGenre.genreId"
            :label="twoGenre.name"
            :value="twoGenre.genreId"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="商品ID" prop="productId">
        <el-input
          v-model="queryParams.productId"
          placeholder="请输入商品ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品编号" prop="productNo">
        <el-input
          v-model="queryParams.productNo"
          placeholder="请输入商品编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="search" size="mini" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['yanjing:product:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['yanjing:product:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['yanjing:product:remove']"
          >删除</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['yanjing:product:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="plus"
          size="mini"
          @click="batchSubmitChangeStatusUpline"
          v-hasPermi="['yanjing:product:batchSubmitChangeStatus']"
          >批量商品上架</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="plus"
          size="mini"
          @click="batchSubmitChangeStatusWaitAudit"
          v-hasPermi="['yanjing:product:batchSubmitChangeStatus']"
          >批量返回待审核</el-button
        >
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="productList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="60"></el-table-column>
      <el-table-column
        label="商品ID"
        align="center"
        prop="productId"
        width="100"
      />
      <el-table-column
        label="一级品类"
        align="center"
        prop="oneGenreName"
        width="100"
      />
      <el-table-column
        label="二级品类"
        align="center"
        prop="twoGenreName"
        width="100"
      />
      <el-table-column
        label="商品编号"
        align="center"
        prop="productNo"
        width="100"
      />
      <el-table-column label="商品名称" align="center" prop="name" />
      <el-table-column
        label="审核状态"
        align="center"
        prop="approveStatus"
        width="100"
      >
        <template #default="scope">
          <dict-tag
            :options="product_approve_status"
            :value="scope.row.approveStatus"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="销售状态"
        align="center"
        prop="onlineStatus"
        width="100"
      >
        <template #default="scope">
          <dict-tag
            :options="product_onlinestatus"
            :value="scope.row.onlineStatus"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="显示顺序"
        align="center"
        prop="floor"
        width="100"
      />
      <el-table-column
        label="市场价(元)"
        align="center"
        prop="listPrice"
        width="100"
      >
        <template #default="scope">
          {{ (Math.round(scope.row.listPrice) / 100).toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="300px"
      >
        <template #default="scope">
          <el-button
            size="mini"
            type="text"
            icon="View"
            @click="handleView(scope.row, scope.index)"
            >详细</el-button
          >
          <!-- <el-button
            size="mini"
            type="text"
            icon="edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['yanjing:product:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['yanjing:product:remove']"
            >删除</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page.sync="queryParams.pageNum"
      v-model:limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
        <el-row>
          <el-col :span="10">
            <el-form-item label="一级品类" prop="oneGenreId">
              <el-select
                v-model="form.oneGenreId"
                placeholder="请选择一级品类"
                clearable
                @change="handleOneProductGenreChange"
              >
                <el-option
                  v-for="oneGenre in oneGenrees"
                  :key="oneGenre.genreId"
                  :label="oneGenre.name"
                  :value="oneGenre.genreId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="二级品类" prop="twoGenreId">
              <el-select
                v-model="form.twoGenreId"
                placeholder="请选择二级品类"
                :disabled="twoGenrees.length === 0"
              >
                <el-option
                  v-for="twoGenre in twoGenrees"
                  :key="twoGenre.genreId"
                  :label="twoGenre.name"
                  :value="twoGenre.genreId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="商品名称" prop="name">
              <el-input
                v-model="form.name"
                type="textarea"
                placeholder="请输入内容"
              />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="商品编号" prop="productNo">
              <el-input v-model="form.productNo" placeholder="请输入商品编号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="10">
            <el-form-item label="显示顺序" prop="floor">
              <el-input v-model="form.floor" placeholder="请输入显示顺序" />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="商品市场价" prop="listPrice">
              <el-input v-model="form.listPrice" placeholder="请输入市场价" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="半染价格" prop="banId">
              <el-select
                v-model="form.banId"
                placeholder="请选择半染价格"
                clearable
              >
                <el-option
                  v-for="banGongYI in banGongYiList"
                  :key="banGongYI.processId"
                  :label="
                    '【' +
                    banGongYI.term +
                    '】' +
                    formatPrice(banGongYI.cost) +
                    '元'
                  "
                  :value="banGongYI.processId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="全染价格" prop="quanId">
              <el-select
                v-model="form.quanId"
                placeholder="请选择全染价格"
                clearable
              >
                <el-option
                  v-for="quanGongYI in quanGongYiList"
                  :key="quanGongYI.processId"
                  :label="
                    '【' +
                    quanGongYI.term +
                    '】' +
                    formatPrice(quanGongYI.cost) +
                    '元'
                  "
                  :value="quanGongYI.processId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="防蓝光工艺" prop="bianseId">
          <el-radio-group
            v-for="item in bianSeList"
            :key="item.processId"
            v-model="form.bianseId"
          >
            <el-col :span="12">
              <el-radio style="left: 5px" :label="item.processId">{{
                item.term
              }}</el-radio>
            </el-col>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item label="基本参数" prop="saleType">
        <el-checkbox-group v-model="saleTypeList">
              <el-col v-for="(item,index) in jiBenPatternList" :key="index" :span="12" :label="item.name">
                <el-checkbox :label="item">{{ item.name }}</el-checkbox>
              </el-col>
            </el-checkbox-group>
        </el-form-item> -->
        <el-form-item label="基本参数" prop="saleType">
          <el-checkbox-group v-model="saleTypeList">
            <el-checkbox
              v-for="item in jiBenPatternList"
              :key="item.patternId"
              :label="item.patternId"
              ><div style="width: 110px">{{ item.name }}</div></el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="个性化定制" prop="dingzhiType">
          <el-checkbox-group v-model="saleTypeList">
            <el-checkbox
              v-for="item in dingzhiPatternList"
              :key="item.patternId"
              :label="item.patternId"
              ><div style="width: 110px">{{ item.name }}</div></el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button v-if="isDetail" type="primary" @click="submitForm"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  queryPageByParam,
  delProduct,
  getProduct,
  addProduct,
  updateProduct,
  saveOrUpdate,
  batchSubmitChangeStatus,
} from "@/api/product/product.js";
import {
  loadOneProductGenreList,
  loadTwoProductGenreList,
} from "@/api/product/genre.js";
import { queryPageByParam as quryJiBenPatternList } from "@/api/product/pattern.js";
import { queryPageByParam as queryGongYiList } from "@/api/base/process.js";
import { getCurrentInstance } from "vue";
export default {
  setup() {
    // 获取当前组件实例
    const instance = getCurrentInstance();
    const { product_approve_status } = instance.proxy.useDict(
      "product_approve_status"
    );
    const { product_onlinestatus } = instance.proxy.useDict(
      "product_onlinestatus"
    );

    return {
      product_approve_status,
      product_onlinestatus,
    };
  },
  name: "Product",
  data() {
    return {
      dingzhiPatternList: [],
      saleTypeList: [],
      jiBenPatternList: [],
      bianSeList: [],
      banGongYiList: [],
      quanGongYiList: [],
      selectedItem: null, // 选中的项的 ID
      oneGenrees: [],
      twoGenrees: [],
      // 遮罩层
      loading: true,
      isDetail: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      productList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        step: "OFFLINE",
        companyId: null,
        enterId: null,
        oneGenreId: null,
        twoGenreId: null,
        threeGenreId: null,
        brandId: null,
        productNo: null,
        productType: null,
        name: null,
        status: null,
        floor: null,
        approveStatus: null,
        onlineStatus: null,
        commendStatus: null,
        saleType: null,
        saleWord: null,
        settleCompanyId: null,
        startTime: null,
        endTime: null,
        memo: null,
        packag: null,
        totalSold: null,
        listPrice: null,
        salePrice: null,
        settlePrice: null,
        bagnmaiPrice: null,
        startPrice: null,
        endPrice: null,
        buyNumber: null,
        productNumber: null,
        firstRatio: null,
        waitTime: null,
        fenqi: null,
        booking: null,
        imageOne: null,
        imageTwo: null,
        imageThree: null,
        imageFour: null,
        imageFive: null,
        totalScore: null,
        averageScore: null,
        banId: null,
        quanId: null,
        bianseId: null,
        bianseColor: null,
        createTime: null,
        createEmployeeId: null,
        updateTime: null,
        updateEmployeeId: null,
        commentTime: null,
        onlineTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
    };
  },
  created() {
    this.getList();
    this.loadOneProductGenre();
    this.queryQuanGongYiList();
    this.queryBanGongYiList();
    this.queryBianseList();
    this.quryJiBenPatternList();
    this.quryDingZhiPatternList();
  },
  methods: {
    queryQuanGongYiList() {
      this.loading = true;
      var queryGongYiform = {
        pageNum: 1,
        pageSize: 20,
        type: "GONGYI",
        code: "QUAN",
      };
      queryGongYiList(queryGongYiform).then((response) => {
        this.quanGongYiList = response.rows;
      });
    },
    queryBanGongYiList() {
      this.loading = true;
      var queryGongYiform = {
        pageNum: 1,
        pageSize: 20,
        type: "GONGYI",
        code: "BAN",
      };
      queryGongYiList(queryGongYiform).then((response) => {
        this.banGongYiList = response.rows;
      });
    },
    queryBianseList() {
      this.loading = true;
      var queryGongYiform = {
        pageNum: 1,
        pageSize: 20,
        type: "BIANSE",
      };
      queryGongYiList(queryGongYiform).then((response) => {
        this.bianSeList = response.rows;
      });
    },
    queryBaseList() {
      this.loading = true;
      var queryGongYiform = {
        pageNum: 1,
        pageSize: 20,
        type: "BIANSE",
      };
      queryGongYiList(queryGongYiform).then((response) => {
        this.bianSeList = response.rows;
      });
    },
    quryJiBenPatternList() {
      this.loading = true;
      var quryJiBenPatternform = {
        pageNum: 1,
        pageSize: 20,
        type: "JIBEN",
      };
      quryJiBenPatternList(quryJiBenPatternform).then((response) => {
        this.jiBenPatternList = response.rows;
      });
    },
    quryDingZhiPatternList() {
      this.loading = true;
      var quryJiBenPatternform = {
        pageNum: 1,
        pageSize: 20,
        type: "DINGZHI",
      };
      quryJiBenPatternList(quryJiBenPatternform).then((response) => {
        this.dingzhiPatternList = response.rows;
      });
    },

    formatPrice(value) {
      console.log("value:" + value);
      return (Math.round(value) / 100).toFixed(2);
    },
    // 加载一级数据
    loadOneProductGenre() {
      loadOneProductGenreList().then((response) => {
        this.oneGenrees = response;
      });
    },
    // 加载二级数据
    loadTwoProductGenre(parentid) {
      loadTwoProductGenreList(parentid).then((response) => {
        this.twoGenrees = response;
      });
    },
    // 选择变化时触发
    handleOneProductGenreChange(value) {
      
      if (value === null || value === "") {
        this.twoGenrees = [];
        this.queryParams.twoGenreId = null;
      } else {
        
        this.queryParams.oneGenreId = value; // 变化时清空已选择的
        this.loadTwoProductGenre(value);
      }
    },
    // 选择变化时触发
    // handleTwoProductGenreChange(value) {
    //   this.loadDistricts(value); // 加载对应的数据
    // },
    /** 查询列表 */
    getList() {
      this.loading = true;
      this.queryParams.step = "OFFLINE";
      queryPageByParam(this.queryParams).then((response) => {
        this.productList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleView(row) {
      
      this.open = true;
      // const selectedItem = this.oneGenrees.find(item => item.genreId === (row.oneGenreId+""));
      // if (selectedItem) {
      //   this.selectedItem = selectedItem.genreId;
      // }

      this.form = { ...row };
      this.form.oneGenreId = row.oneGenreId + "";
      this.loadTwoProductGenre(row.oneGenreId);
      this.form.twoGenreId = row.twoGenreId + "";
      this.form.banId = row.banId + "";
      this.form.quanId = row.quanId + "";
      this.form.bianseId = row.bianseId + "";
      this.form.listPrice = (Math.round(row.listPrice) / 100).toFixed(2);
      this.saleTypeList = row.saleType.split(",");
      this.isDetail = false;
      this.title = "商品信息"
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.isDetail = true;
      this.saleTypeList = [];
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        productId: null,
        companyId: null,
        enterId: null,
        oneGenreId: null,
        twoGenreId: null,
        threeGenreId: null,
        brandId: null,
        productNo: null,
        productType: null,
        name: null,
        status: null,
        floor: null,
        approveStatus: null,
        onlineStatus: null,
        commendStatus: null,
        saleType: null,
        saleWord: null,
        settleCompanyId: null,
        startTime: null,
        endTime: null,
        memo: null,
        packag: null,
        totalSold: null,
        listPrice: null,
        salePrice: null,
        settlePrice: null,
        bagnmaiPrice: null,
        startPrice: null,
        endPrice: null,
        buyNumber: null,
        productNumber: null,
        firstRatio: null,
        waitTime: null,
        fenqi: null,
        booking: null,
        imageOne: null,
        imageTwo: null,
        imageThree: null,
        imageFour: null,
        imageFive: null,
        totalScore: null,
        averageScore: null,
        banId: null,
        quanId: null,
        bianseId: null,
        bianseColor: null,
        createTime: null,
        createEmployeeId: null,
        updateTime: null,
        updateEmployeeId: null,
        commentTime: null,
        onlineTime: null,
      };
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.productId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.isDetail = true;
      this.reset();
      this.open = true;
      this.title = "添加商品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      
      this.isDetail = true;
      this.reset();
      const productId = row.productId || this.ids;
      getProduct(productId).then((response) => {
        
        this.form = response.data;
        this.form.oneGenreId = response.data.oneGenreId + "";
        this.loadTwoProductGenre(response.data.oneGenreId);
        this.form.twoGenreId = response.data.twoGenreId + "";
        this.open = true;
        this.form.listPrice = (
          Math.round(response.data.listPrice) / 100
        ).toFixed(2);
        this.form.banId = response.data.banId + "";
        this.form.quanId = response.data.quanId + "";
        this.form.bianseId = response.data.bianseId + "";
        this.saleTypeList = response.data.saleType.split(",");

        this.title = "修改商品";
      });
    },

    convertYuanToFen(str) {
      // 正则表达式匹配包含两位小数的数字，并将其替换为分的整数部分
      return str.replace(/(\d+)(\.\d{2})/g, function (match, p1, p2) {
        return p1 * 100 + Math.round(parseFloat(p2) * 100);
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.saleType = this.saleTypeList.join(",");
          this.form.listPrice = this.convertYuanToFen(this.form.listPrice);
          if (this.form.productId != null) {
            saveOrUpdate(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            saveOrUpdate(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const productIds = row.productId || this.ids;
      this.$modal
        .confirm(
          '是否确认删除编号为"' + productIds + '"的数据项？'
        )
        .then(function () {
          return delProduct(productIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "yanjing/product/export",
        {
          ...this.queryParams,
        },
        `product_${new Date().getTime()}.xlsx`
      );
    },

    batchSubmitChangeStatusUpline() {
      this.batchSubmitChangeStatus("ONLINE");
    },
    batchSubmitChangeStatusWaitAudit() {
      this.batchSubmitChangeStatus("UNVERIFIED");
    },

    async batchSubmitChangeStatus(status) {
      const productIds = this.ids;
      if (productIds == "") {
        alert("请选择需要提交的数据.");
        return;
      }
      var approveStatus = "UNVERIFIED";
      if (status != null && status != undefined && status != "") {
        approveStatus = status;
      }
      var message = "";
      if ("UNVERIFIED" === approveStatus) {
        message = "是否提交审核所选商品信息?";
      }
      if ("PASS" === approveStatus) {
        message = "是否审核通过所选商品信息?";
      }
      if ("COMMEND" === approveStatus) {
        message = "是否审核通过并推荐所选商品信息?";
      }
      if ("FAIL" === approveStatus) {
        message = "是否审核不通过所选商品信息?";
      }
      if ("ONLINE" === approveStatus) {
        message = "是否上架所选商品信息?";
      }
      if ("OFFLINE" === approveStatus) {
        message = "是否批量返回待审核所选商品信息?";
      }
      if ("DOWN_OFFLINE" === approveStatus) {
        message = "是否下架所选商品信息?";
      }

      this.$modal
        .confirm("编号为" + productIds + "的商品已被选择" + message)
        .then(function () {
          return batchSubmitChangeStatus({
            productIds: productIds,
            approveStatus: approveStatus,
          });
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("提交成功");
        })
        .catch(() => {});
    },
  },
};
</script>
